﻿using System.Net.Http.Json;
using Devonline.AspNetCore;
using Microsoft.Extensions.Logging;

namespace Devonline.CloudService.Xfyun.FaceRecognition.FaceCompare;

/// <summary>
/// 人脸识别相关服务
/// </summary>
/// <param name="logger"></param>
/// <param name="endpoint"></param>
/// <param name="httpClientFactory"></param>
public class FaceCompareService(
    ILogger<FaceCompareService> logger,
    IFaceCompareEndpoint endpoint,
    IFileService fileService,
    IHttpClientFactory httpClientFactory
    ) : IFaceRecognitionService
{
    private readonly ILogger<FaceCompareService> _logger = logger;
    private readonly IFaceCompareEndpoint _endpoint = endpoint;
    private readonly IFileService _fileService = fileService;
    private readonly IHttpClientFactory _httpClientFactory = httpClientFactory;
    private const string IMAGE_CUT_PREFIX = "fc_";

    /// <summary>
    /// 人脸比对
    /// </summary>
    /// <param name="src">原图片</param>
    /// <param name="dist">比较图片</param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<(bool, float)> CompareAsync(string src, string dist)
    {
        _logger.LogInformation($"将使用讯飞云接口比较两张面部照片: {src} 和 {dist} 的相似度");
        src = (await _fileService.GetImageCropFileAsync(src, _endpoint.ImageLimit))!;
        dist = (await _fileService.GetImageCropFileAsync(dist, _endpoint.ImageLimit))!;

        var url = new AuthorizationModel(_endpoint).ToString();
        var body = new RequestModel(_endpoint.Id, src, dist);
        var httpClient = _httpClientFactory.CreateClient(nameof(FaceCompareService));
        using var response = await httpClient.PostAsJsonAsync(_endpoint.Path + url, body);
        if (!response.IsSuccessStatusCode)
        {
            throw new ArgumentException($"人脸比对失败, 服务器相应失败: {response.StatusCode}, 错误详情: " + await response.Content.ReadAsStringAsync());
        }

        var responseModel = await response.Content.ReadFromJsonAsync<ResponseModel>() ?? throw new Exception("人脸比对接口调用成功, 但是返回值无法正确序列化!");
        if (responseModel.Header.Code != UNIT_ZERO || responseModel.Payload is null || responseModel.Payload.FaceCompareResult is null || responseModel.Payload.FaceCompareResult.Result is null || responseModel.Payload.FaceCompareResult.Result.Return != UNIT_ZERO)
        {
            throw new ArgumentException("人脸比对失败, 详见接口返回结果: " + responseModel.ToJsonString());
        }

        var result = responseModel.Payload.FaceCompareResult.Result.Score >= _endpoint.FaceCompareThresholdValue;
        _logger.LogInformation($"使用讯飞云接口比较两张面部照片: {src} 和 {dist} 的相似度, 比较完成, 人脸比对得分: {responseModel.Payload.FaceCompareResult.Result.Score} " + (result ? $"高于阈值: {_endpoint.FaceCompareThresholdValue}, 判定为同一人!" : $"低于阈值: {_endpoint.FaceCompareThresholdValue}, 判定为不是同一人!"));
        return (result, responseModel.Payload.FaceCompareResult.Result.Score);
    }
}